package com.ruoyi.shopping.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dto.*;
import com.ruoyi.sale.domain.MallBrands;
import com.ruoyi.sale.domain.MallCouponProductRegionRelation;
import com.ruoyi.sale.mapper.*;
import com.ruoyi.shopping.domain.*;
import com.ruoyi.shopping.mapper.*;
import com.ruoyi.vo.MallProductByOneVo;
import com.ruoyi.vo.MallProductNameVo;
import com.ruoyi.vo.MallProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.shopping.service.IMallProductService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品管理Service业务层处理
 *
 * @author cws
 * @date 2024-11-19
 */
@Service
@Slf4j
public class MallProductServiceImpl implements IMallProductService {
    @Autowired
    private MallProductMapper mallProductMapper;

    @Autowired
    private MallSkusMapper mallSkusMapper;

    @Autowired
    private MallProSkuMapper mallProSkuMapper;

    @Autowired
    private MallProductLadderMapper mallProductLadderMapper;

    @Autowired
    private MallProductFullReductionMapper mallProductFullReductionMapper;

    @Autowired
    private MallBrandsMapper mallBrandsMapper;

    @Autowired
    private MallRegionsMapper mallRegionsMapper;

    @Autowired
    private MallCouponProductRegionRelationMapper mallCouponProductRegionRelationMapper;

    @Autowired
    private MallCouponProductRelationMapper mallCouponProductRelationMapper;

    @Autowired
    private MallHomeNewProductMapper mallHomeNewProductMapper;

    @Autowired
    private MallHomeRecommendProductMapper mallHomeRecommendProductMapper;


    /**
     * 查询商品管理
     *
     * @param id 商品管理主键
     * @return 商品管理
     */
    @Override
    public MallProductByOneVo selectMallProductById(Long id) {
        MallProductByOneVo mallProductByOneVo = new MallProductByOneVo();
//        获取商品
        MallProduct mallProduct = mallProductMapper.selectMallProductById(id);
        BeanUtils.copyProperties(mallProduct, mallProductByOneVo);
        //获取sku
        List<MallSkus> skuList = mallSkusMapper.selectMallSkusOfPro(id);
        mallProductByOneVo.setSkuList(skuList);
        MallBrands mallBrands = mallBrandsMapper.selectMallBrandsById(mallProduct.getBrandId());
        mallProductByOneVo.setBrandName(mallBrands.getName());
        MallRegions mallRegions = mallRegionsMapper.selectMallRegionsById(mallProduct.getRegionId());
        mallProductByOneVo.setRegionName(mallRegions.getName());
        //获取销售
        if (mallProduct.getPromotionType().equals(1l)) {//阶梯
            List<MallProductLadder> ladderArr = mallProductLadderMapper.selectMallProductLadderByList(id);
            mallProductByOneVo.setLadderArr(ladderArr);
        } else if (mallProduct.getPromotionType().equals(2l)) {//满减
            List<MallProductFullReduction> fullArr = mallProductFullReductionMapper.selectMallProductFullReductionByList(id);
            mallProductByOneVo.setFullArr(fullArr);
        }
        mallProductByOneVo.setProductHtml(mallProduct.getDetailHtml());
        return mallProductByOneVo;
    }

    /**
     * 查询商品管理列表
     *
     * @param mallProduct 商品管理
     * @return 商品管理
     */
    @Override
    public List<MallProduct> selectMallProductList(MallProduct mallProduct) {
        return mallProductMapper.selectMallProductList(mallProduct);
    }

    /**
     * 新增商品管理
     *
     * @param mallProduct 商品管理
     * @return 结果
     */
    @Override
    public int insertMallProduct(MallProduct mallProduct) {
        mallProduct.setCreateTime(DateUtils.getNowDate());
        return mallProductMapper.insertMallProduct(mallProduct);
    }

    /**
     * 修改商品管理
     *
     * @param mallProductAddOrUpdateDto 商品管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMallProduct(MallProductAddOrUpdateDto mallProductAddOrUpdateDto) {
        //        1.修改详情
        MallProduct mallProduct = new MallProduct();
        BeanUtils.copyProperties(mallProductAddOrUpdateDto, mallProduct);
        if (!Objects.isNull(mallProductAddOrUpdateDto.getSkuList())&&mallProductAddOrUpdateDto.getSkuList().size()>0) {
            //  计算sku库存
            Long stock = mallProductAddOrUpdateDto.getSkuList().stream().mapToLong(MallSkuDto::getStock).sum();
            mallProduct.setStock(stock);
        }
        if (SecurityUtils.getUsername().equals("admin")) {
            mallProduct.setVerifyStatus(1l);
        } else {
            mallProduct.setVerifyStatus(0l);
        }
        mallProduct.setDetailHtml(mallProductAddOrUpdateDto.getProductHtml());
        mallProduct.setCreateTime(DateUtils.getNowDate());
        mallProduct.setUpdateTime(DateUtils.getNowDate());
        int i = mallProductMapper.updateMallProduct(mallProduct);
        log.info("修改商品结果：" + i);


        Long productId = mallProduct.getId();
        if (mallProductAddOrUpdateDto.getSkuList() != null && mallProductAddOrUpdateDto.getSkuList().size() > 0) {
//           mysql做了触发器 只需要删除 mall_pro_sku表即可
            int delRes = mallProSkuMapper.deleteMallProSkuByProId(productId);
            log.info("删除mall_pro_sku表结果：" + delRes);
            List<MallSkuDto> skuList = mallProductAddOrUpdateDto.getSkuList();
            List<MallSkus> mallSkusList = skuList.stream().map(item -> {
                MallSkus mallSkus = new MallSkus();
                BeanUtils.copyProperties(item, mallSkus);
                return mallSkus;
            }).collect(Collectors.toList());
            Boolean res = mallSkusMapper.bacthMallSkus(mallSkusList);
            log.info("批量插入sku表结果：" + res);
            List<MallProSku> mallProSkus = mallSkusList.stream().map(item -> {
                MallProSku mallProSku = new MallProSku();
                mallProSku.setProId(productId);
                mallProSku.setSkuId(item.getId());
                return mallProSku;
            }).collect(Collectors.toList());
            Boolean proSkuRes = mallProSkuMapper.backtMallProSku(mallProSkus);
            log.info("批量插入关联表结果：" + proSkuRes);
        }
//        4.添加销售表
        //4.1 满减
        List<MallProductFullReductionDto> fullArr = mallProductAddOrUpdateDto.getFullArr().stream().map(item -> {
            item.setProductId(productId);
            return item;
        }).collect(Collectors.toList());
        //4.2 阶梯
        List<MallProductLadderDto> ladderArr = mallProductAddOrUpdateDto.getLadderArr().stream().map(item -> {
            item.setProductId(productId);
            return item;
        }).collect(Collectors.toList());
        //4.1 阶梯
        if (mallProductAddOrUpdateDto.getPromotionType().equals(1l)) {
            //查询是够有数据
            int count = mallProductLadderMapper.selectMallProductLadderCount(productId);
            if (count > 0) {
                mallProductLadderMapper.backUpdateMallProductLadder(ladderArr);
            } else {
                mallProductLadderMapper.backMallProductLadder(ladderArr);
            }
        } else if (mallProductAddOrUpdateDto.getPromotionType().equals(2L)) {
            int count = mallProductFullReductionMapper.selectMallProductFullReductionCount(productId);
            if (count > 0) {
                mallProductFullReductionMapper.batchUpdateMallProductFullReduction(fullArr);
            } else {
                mallProductFullReductionMapper.batchMallProductFullReduction(fullArr);
            }
        }
        return 1;
    }

    /**
     * 批量删除商品管理
     *
     * @param ids 需要删除的商品管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteMallProductByIds(Long[] ids) {
//        1.删除商品
        int i = mallProductMapper.deleteMallProductByIds(ids);
        delProductOutTable(ids);
        return 1;
    }

    private void delProductOutTable(Long[] ids) {
        for (Long id : ids) {
            //        2.删除商品sku表绑定表
            mallProSkuMapper.deleteMallProSkuByProId(id);
//            3.删除优惠卷商品关联表
            mallCouponProductRelationMapper.deleteByProductRelationByProductId(id);
//            4.删除商品满减表
            mallProductFullReductionMapper.deleteMallProductFullReductionByProductId(id);
//            5.删除商品阶梯表
            mallProductLadderMapper.deleteMallProductLadderByProductId(id);
//           6.删除新品推荐
            mallHomeNewProductMapper.removeMallHomeNewProductById(id);
//             7.删除推荐商品
            mallHomeRecommendProductMapper.removeMallHomeRecommendProductById(id);
        }
    }
    /**
     * 删除商品管理信息
     *
     * @param id 商品管理主键
     * @return 结果
     */
    @Override
    public int deleteMallProductById(Long id) {
        return mallProductMapper.deleteMallProductById(id);
    }

    @Override
    public List<MallProductVo> selectMallProductListVO(ProductParams params) {
        List<MallProductVo> list = null;
        if (params.getType().equals("new")) {
            list = mallProductMapper.selectMallProductListVoNew(params);
        } else if (params.getType().equals("hot")) {
            list = mallProductMapper.selectMallProductListVoHto(params);
        } else {
            list = mallProductMapper.selectMallProductListVO(params);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int SaveMallProduct(MallProductAddOrUpdateDto mallProductAddOrUpdateDto) {
//        1.添加商品表
        MallProduct mallProduct = new MallProduct();
        BeanUtils.copyProperties(mallProductAddOrUpdateDto, mallProduct);
        if (!Objects.isNull(mallProductAddOrUpdateDto.getSkuList())&&mallProductAddOrUpdateDto.getSkuList().size()>0) {
            //        计算sku库存
            Long stock = mallProductAddOrUpdateDto.getSkuList().stream().mapToLong(MallSkuDto::getStock).sum();
            mallProduct.setStock(stock);
        }
        if (SecurityUtils.getUsername().equals("admin")) {
            mallProduct.setVerifyStatus(1l);
        } else {
            mallProduct.setVerifyStatus(0l);
        }
        mallProduct.setDetailHtml(mallProductAddOrUpdateDto.getProductHtml());
        mallProduct.setCreateTime(DateUtils.getNowDate());
        mallProductMapper.insertMallProduct(mallProduct);
        log.info("添加商品表结果：" + mallProduct.getId());
        //        2.添加商品sku表
        Long productId = mallProduct.getId();
        if (mallProductAddOrUpdateDto.getSkuList() != null && mallProductAddOrUpdateDto.getSkuList().size() > 0) {
//         2.1转换对象
            List<MallSkuDto> skuList = mallProductAddOrUpdateDto.getSkuList();
            List<MallSkus> mallSkusList = skuList.stream().map(item -> {
                MallSkus mallSkus = new MallSkus();
                BeanUtils.copyProperties(item, mallSkus);
                return mallSkus;
            }).collect(Collectors.toList());
//        2.2添加sku表
            Boolean res = mallSkusMapper.bacthMallSkus(mallSkusList);
            log.info("批量插入sku表结果：" + res);
//        3.添加关联表
//        3.1建立连接
            List<MallProSku> mallProSkus = mallSkusList.stream().map(item -> {
                MallProSku mallProSku = new MallProSku();
                mallProSku.setProId(productId);
                mallProSku.setSkuId(item.getId());
                return mallProSku;
            }).collect(Collectors.toList());
            Boolean proSkuRes = mallProSkuMapper.backtMallProSku(mallProSkus);
            log.info("批量插入关联表结果：" + proSkuRes);
        }

//        4.添加销售表
        //4.1 满减
        List<MallProductFullReductionDto> fullArr = mallProductAddOrUpdateDto.getFullArr().stream().map(item -> {
            item.setProductId(productId);
            return item;
        }).collect(Collectors.toList());
        //4.2 阶梯
        List<MallProductLadderDto> ladderArr = mallProductAddOrUpdateDto.getLadderArr().stream().map(item -> {
            item.setProductId(productId);
            return item;
        }).collect(Collectors.toList());
        //4.1 阶梯
        if (mallProductAddOrUpdateDto.getPromotionType().equals(1l)) {
            mallProductLadderMapper.backMallProductLadder(ladderArr);
        } else if (mallProductAddOrUpdateDto.getPromotionType().equals(2l)) {
            mallProductFullReductionMapper.batchMallProductFullReduction(fullArr);
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSku(List<MallSkus> mallSkusList) {
        mallSkusList.forEach(item -> {
            mallSkusMapper.updateMallSkus(item);
        });
        return 1;
    }

    @Override
    public List<MallProductNameVo> SelectProductName(String name) {
        return mallProductMapper.SelectProductName(name);
    }

    @Override
    public int updateVerifyStatus(Long id) {
        return mallProductMapper.updateVerifyStatus(id);
    }
}
